package com.jjh.springframework.core.io;

import cn.hutool.core.util.ClassUtil;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

/**
 * ClassPathResource
 * 这一部分的实现是用于通过 ClassLoader 读取 ClassPath 下的文件信息，
 * 具体的读取过程主要是：classLoader.getResourceAsStream(path)
 *
 * @author jjh
 * @date 2021/06/13
 **/
public class ClassPathResource implements Resource {

    private final String path;

    private ClassLoader classLoader;

    public ClassPathResource(String path) {
        this(path, null);
    }

    public ClassPathResource(String path, ClassLoader classLoader) {
        this.path = path;
        this.classLoader = classLoader != null ? classLoader : ClassUtil.getContextClassLoader();
    }

    @Override
    public InputStream getInputStream() throws IOException {
        InputStream steam = classLoader.getResourceAsStream(path);
        if (steam == null) {
            throw new FileNotFoundException(this.path + " cannot be opened because it does not exist.");
        }
        return steam;
    }
}
